package lucene.server.web.dao;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lucene.server.common.model.*;
import lucene.server.common.utils.ReflectUtil;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class SystemDao {

    @SneakyThrows
    public static   <T> T  findOne(Object object, Class<T> clazz){
        Table tableInfo = ReflectUtil.getTableAnnotation(object);
        if (tableInfo == null){ throw  new RuntimeException("没有注解");}
        Object keyValue =  ReflectUtil.getFieldValue(object,tableInfo.key());
        if(keyValue == null){
            throw  new RuntimeException(keyValue+"没有值");
        }
        List<T> results =  Db.use().find(Entity.create(tableInfo.name()).set(tableInfo.key(),keyValue),clazz);
        return results.stream()
                .findFirst()
                .orElse(null);
    }

    @SneakyThrows
    public static int deleteAll(String tableName){
         return Db.use().del(Entity.create(tableName));
    }

    @SneakyThrows
    public static int insertOrUpdate(Object object){
        Table tableInfo = ReflectUtil.getTableAnnotation(object);
        if (tableInfo == null){ throw  new RuntimeException("没有注解");}
        Object keyValue =  ReflectUtil.getFieldValue(object,tableInfo.key());
        if(keyValue == null){
            ReflectUtil.setFieldValue(object,tableInfo.key(),String.valueOf(System.currentTimeMillis()));
        }
        return Db.use().insertOrUpdate(Entity.create(tableInfo.name()).parseBean(object),tableInfo.key());
    }
    @SneakyThrows
    public static boolean checkExists(Object object,String... keys){
        Table tableInfo = ReflectUtil.getTableAnnotation(object);
        if (tableInfo == null){ throw  new RuntimeException("没有注解");}

        final Entity where = new Entity(tableInfo.name());
        for (String key : keys) {
            if (!where.containsKey(key)) {
                where.set(key,ReflectUtil.getFieldValue(object,key));
            }
        }
        return  Db.use().count(where)>0 ? true : false;
    }
    @SneakyThrows
    public static int delete(Object object){
        Table tableInfo = ReflectUtil.getTableAnnotation(object);
        if (tableInfo == null){ throw  new RuntimeException("没有注解");}
        Object keyValue =  ReflectUtil.getFieldValue(object,tableInfo.key());
        if(keyValue == null){
            throw  new RuntimeException(keyValue+"没有值");
        }
        return Db.use().del(Entity.create(tableInfo.name()).set(tableInfo.key(),keyValue));
    }
    @SneakyThrows
    public static PageResult<Entity> getPageAll(String tableName, int page, int num,Order order){
        Page  dbpage = new Page(page,num);
        if (order!=null){
            dbpage.setOrder(order);
        }
        return Db.use().page(Entity.create(tableName),dbpage);
    }

    public static List<?> getAll(String tableName, Class<?> clazz) throws SQLException {
        return Db.use().findAll(Entity.create(tableName),clazz);
    }

    public static Map<String,Object> getJoblog(int page){
        Order order = new Order("begintime", Direction.DESC);
        PageResult<Entity> result = SystemDao.getPageAll("sys_log", page,10,order);
        Map<String,Object> map = new HashMap<>();
        map.put("data",result);
        map.put("totalPage",result.getTotalPage());
        map.put("total",result.getTotal());
        map.put("page",result.getPage());
        return map;
    }
    public static int updateSystemParam(List< Map<String,String>> values) throws SQLException {
        Db.use().tx(db -> {
            for (Map<String, String> value : values) {
                db.update(
                    Entity.create().set("value",  value.get("value")),
                    Entity.create("setting").set("param", value.get("param"))
                );
            }
        });
        return values.size();
    }


}
